package com.itheima.factory;


import lombok.experimental.var;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.Date;
import java.util.ResourceBundle;

public class BeanFactory {
    public static Object getBean(String beanId){

        try {
            ResourceBundle beanIds = ResourceBundle.getBundle("beanId");
            String className = beanIds.getString(beanId);
            Class<?> clazz = Class.forName(className);
            Object bean = clazz.newInstance();
            InvocationHandler invocationHandler = new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    Object invoke = null;
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.append("时间:"+new Date().toLocaleString()).append(", 类名:"+
                    bean.getClass().getName()).append(", 方法名:"+method.getName()).
                            append(", 入参:"+ Arrays.toString(args));
                    try {
                        invoke = method.invoke(bean, args);
                    }catch (Exception e){
                        stringBuilder.append(e.getMessage());
                        throw e;
                    }
                    System.out.println(stringBuilder.toString());

                    return invoke;
                }
            };
            Object obj = Proxy.newProxyInstance(bean.getClass().getClassLoader(),
                    bean.getClass().getInterfaces(), invocationHandler);
            return obj;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

}
